package com.sunday.shoufen.ui.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.common.widgets.swipe.Closeable;
import com.sunday.common.widgets.swipe.OnSwipeMenuItemClickListener;
import com.sunday.common.widgets.swipe.SwipeMenu;
import com.sunday.common.widgets.swipe.SwipeMenuCreator;
import com.sunday.common.widgets.swipe.SwipeMenuItem;
import com.sunday.common.widgets.swipe.SwipeMenuRecyclerView;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.BankAccountlistAdapter;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.entity.BankAccount;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.AddBankAccountActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.common.widgets.EmptyLayout.HIDE_LAYOUT;
import static com.sunday.common.widgets.EmptyLayout.NODATA;


/**
 * Created by 刘涛 on 2017/10/24.
 */

public class SelectAccountActivity extends BaseActivity {

    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private long memberId;
    private List<BankAccount> dataSet = new ArrayList<>();
    private BankAccountlistAdapter adapter;
    private LinearLayoutManager layoutManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_account);
        ButterKnife.bind(this);
        initView();
        getData();
    }

    private void initView() {
        titleView.setText("提现到银行卡");
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setImageResource(R.mipmap.add);
        memberId = BaseApp.getInstance().getMember().getId();
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new BankAccountlistAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BankAccount item = (BankAccount) v.getTag();
                Intent data = new Intent();
                data.putExtra("item", item);
                setResult(RESULT_OK, data);
                finish();
            }
        });

        //右滑菜单
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        recyclerView.setSwipeMenuItemClickListener(menuItemClickListener);

    }


    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.d60);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            SwipeMenuItem deleItem = new SwipeMenuItem(mContext).setBackgroundDrawable(R.color.main_color)
                    .setText("解绑")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleItem);

        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        @Override
        public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, @SwipeMenuRecyclerView.DirectionMode int direction) {
            switch (direction) {
                case SwipeMenuRecyclerView.LEFT_DIRECTION:
                    break;
                case SwipeMenuRecyclerView.RIGHT_DIRECTION:
                    closeable.smoothCloseMenu();//关闭被点击的菜单
                    AlertDialog dialog = new AlertDialog.Builder(mContext).setTitle("温馨提示")
                            .setMessage("确认解绑吗")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteAccount(dataSet.get(adapterPosition).getId());
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
                    break;
            }
        }
    };

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<BankAccount>>> call = ApiClient.getApiAdapter().getMemberBank(memberId,1);
        call.enqueue(new Callback<ResultDO<List<BankAccount>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<BankAccount>>> call, Response<ResultDO<List<BankAccount>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    dataSet.clear();
                    dataSet.addAll(response.body().getResult());
                    emptyLayout.setErrorType(dataSet.size() > 0 ? HIDE_LAYOUT : NODATA);
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<BankAccount>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private void deleteAccount(long prdId) {
        Call<ResultDO> call = ApiClient.getApiAdapter().deleteCard(prdId);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    @OnClick({R.id.right_btn})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_btn:
                intent = new Intent(mContext, AddBankAccountActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }
}
